package Month11.Day25;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.SAXWriter;
import org.dom4j.io.XMLWriter;

import java.io.*;
import java.util.List;
import java.util.Scanner;

public class Test3 {
    public static void main(String[] args) throws IOException {
        String path = "D:\\中国玩家\\products.xml";
        SAXReader reader = new SAXReader();
        Document doc = null;
        try {
            doc = reader.read(new File(path));
            List<Element> list = doc.selectNodes("/shop/product");
            Scanner in = new Scanner(System.in);
            System.out.println("请输入商品的编号：");
            int number = in.nextInt();
            boolean flag = true;
            System.out.println("请输入商品的库存数量");
            int count = in.nextInt();
            String count1 = String.valueOf(count);
            for (Element e : list) {
                int itemno = Integer.parseInt(e.selectSingleNode("itemno").getText());
                if (number == itemno) {
                    System.out.println("商品编号输入正确，需要更改库存的商品为：" + e.selectSingleNode("name").getText());
                    e.selectSingleNode("stockcount").setText(count1);
                    flag = false;

                }

            }
            if (flag) {
                System.out.println("输入的商品编号错误，请重新输入");
            }
        } catch (DocumentException e) {

            e.printStackTrace();
            return;
        }
        OutputFormat format = OutputFormat.createPrettyPrint();
        format.setEncoding("utf-8");
        try {
            XMLWriter xm = new XMLWriter(new FileWriter("D:\\中国玩家\\products.xml"), format);
            xm.write(doc);
            xm.close();
            System.out.println("xie ru chenggong");
        } catch (IOException e) {
            e.printStackTrace();
        }

    }


}

